<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>风险评估管理</title>
    <link rel="stylesheet" type="text/css" href="/static/layui/css/layui.css" />
    <style>
        body { font-family: Arial, sans-serif; }
        .container { width: 98%; margin: 0 auto; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; }
        .form-group input, .form-group select { width: 100%; padding: 8px; box-sizing: border-box; }
        .btn { padding: 10px 15px; background-color: #007BFF; color: white; border: none; cursor: pointer; align-items: center; justify-content: center; }
        .btn:hover { background-color: #0056b3; }
        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
        table, th, td { border: 1px solid #ddd; }
        th, td { padding: 10px; text-align: left; }
        th { background-color: #f2f2f2; }
        .header-container { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
        .layui-table-cell { height: auto !important; overflow: visible !important; }
        .layui-table-view .layui-table { overflow: visible; }
        .layui-table-view .layui-table[lay-filter="riskAssessmentTable"] .layui-table-cell { overflow: visible; }
        .layui-form-select dl { max-height: 200px !important; position: absolute; z-index: 1000; width: 100%; background-color: #fff; border: 1px solid #e6e6e6; border-radius: 2px; box-shadow: 0 2px 4px rgba(0, 0, 0, .12); }
        .auto-wrap {
            white-space: pre-wrap;
            word-wrap: break-word;
            max-width: 100%;
        }
        /* 新增样式，确保下拉框和按钮在同一行 */
        .layui-form .layui-input-inline {
            display: flex;
            align-items: center;
        }
        .layui-form .layui-input-inline .layui-btn {
            margin-left: 10px;
        }
         /* 统一设置所有 layui-input 的样式 */
        .layui-input {
            width: 120px; /* 设置宽度为 100px */
            margin-right: 12px;
            align-content: center;
            display: block; /* 使 margin: 0 auto 生效 */
        }

    </style>
</head>
<body>
    <div class="container">
        <div class="layui-form" id="table-list">
            <table class="layui-hide" id="riskAssessmentTable" lay-filter="riskAssessmentTable"></table>
        </div>
    </div>

    <script src="/static/js/jquery-3.6.0.min.js"></script>
    <script src="/static/layui/layui.js" type="text/javascript" charset="utf-8"></script>
    <script src="/static/js/common.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/html" id="toolbarTop">
        <form class="layui-form" id="filterForm">
            <div class="layui-input-inline">

                <input type="text" name="filter_item"    placeholder="- ITEM -" lay-affix="clear" class="layui-input" >
                <input type="text" name="filter_ecu"     placeholder="- 零部件 -" lay-affix="clear" class="layui-input" >
                <input type="text" name="filter_feature" placeholder="- 资产 -" lay-affix="clear" class="layui-input" >
                <input type="text" name="filter_security" placeholder="- 安全属性 -" lay-affix="clear" class="layui-input" >
                <input type="text" name="filter_affect_level" placeholder="- 影响等级 -" lay-affix="clear" class="layui-input" >

                <button class="layui-btn layui-btn-sm" lay-submit lay-filter="filterSubmit">
                    <i class="layui-icon layui-icon-search"></i>搜索</button>
                <button class="layui-btn layui-btn-primary layui-btn-sm" id="clearFilter">取消</button>
                 <div style="margin-left: 30px;">
                        批量修改
                        <input type="checkbox" name="enableCheckBox"
                               lay-filter="enableCheckBox"
                               lay-skin="switch"
                               lay-text="ON|OFF">
                 </div>
            </div>
        </form>
    </script>

    <script>
        {#import layui from "../../static/echars/echarts";#}

        layui.use(['table', 'form', 'layer'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            {#var tableInstance = null; // 用于保存表格实例#}
            {#var switchHandlerAdded = false;#}

            // 监听 enableCheckBox 复选框的状态改变事件
            form.on('switch(enableCheckBox)', function(data){
                // 获取当前复选框的状态
                var isChecked = data.elem.checked;
                // 根据状态显示不同的消息
                var message = isChecked ? '进入批量修改模式' : '退出批量修改模式';
                // 弹出消息
                layer.msg(message);

                // 根据复选框的状态显示或隐藏表格的checkbox列
                if(isChecked) {
                    table.hideCol('riskAssessmentTable', {
                        field: 'checkboxCol', // 对应表头的 field 属性值
                        hide: false // `true` or `false`);
                    });
                } else {
                    console.log('isChecked off', isChecked)
                    table.hideCol('riskAssessmentTable', {
                        field: 'checkboxCol', // 对应表头的 field 属性值
                        hide: true // `true` or `false`);
                    });
                    // 取消所有被选择的条目
                    table.setRowChecked('riskAssessmentTable', {
                        index: 'all', // 所有行
                        checked: false // 此处若设置 true，则表示全选
                    });
                }
            });

            // 监听 filterSubmit 按钮的提交事件
            form.on('submit(filterSubmit)', function (data) {
                console.log('搜索条件:', data.field); // 打印表单数据

                // 获取用户选择的过滤条件
                var filterData = data.field;
                // 保存输入框的值
                var filterItemValue = $('input[name="filter_item"]').val();
                var filterEcuValue = $('input[name="filter_ecu"]').val();
                var filterFeatureValue = $('input[name="filter_feature"]').val();
                var filterSecurityValue = $('input[name="filter_security"]').val();
                var filterAffectLevelValue = $('input[name="filter_affect_level"]').val();

                // 重新加载表格数据，并传递过滤条件
                table.reloadData('riskAssessmentTable', {
                    where: filterData,
                    page: {
                        curr: 1 // 重新从第一页开始
                    },
                    done: function (res, curr, count) {
                        // 表格重新加载完成后，重新为输入框赋值
                        $('input[name="filter_item"]').val(filterItemValue);
                        $('input[name="filter_ecu"]').val(filterEcuValue);
                        $('input[name="filter_feature"]').val(filterFeatureValue);
                        $('input[name="filter_security"]').val(filterSecurityValue);
                        $('input[name="filter_affect_level"]').val(filterAffectLevelValue);
                    }
                });

                return false; // 阻止表单默认提交行为
            });

            // 获取下拉框选项
            var safeAffectOptions = [];
            var economyAffectOptions = [];
            var operatorAffectOptions = [];
            var privateAffectOptions = [];

            Promise.all([
                fetch('/getRiskAssessmentPara?type=安全影响').then(response => response.json()),
                fetch('/getRiskAssessmentPara?type=经济影响').then(response => response.json()),
                fetch('/getRiskAssessmentPara?type=操作影响').then(response => response.json()),
                fetch('/getRiskAssessmentPara?type=隐私影响').then(response => response.json())
            ]).then(data => {
                safeAffectOptions = data[0];
                economyAffectOptions = data[1];
                operatorAffectOptions = data[2];
                privateAffectOptions = data[3];
                renderTable();
            });

            function renderTable() {
                var windowHeight = window.innerHeight;
                var tableHeight = windowHeight - 30;
                // 获取当前switch状态
                {#var initStatus = $('[name="enableCheckBox"]').prop('checked');#}
                table.render({
                    elem: '#riskAssessmentTable',
                    url: '/getRiskAssessmentEcu',
                    id: 'riskAssessmentTable', // 自定义 id 索引
                    height: 'full-20',
                    toolbar: '#toolbarTop',
                    page: true,
                    limit: 20,
                    limits: [20, 50, 100, 500, 1000],
                    cols: [[
                        {type: 'checkbox', field: 'checkboxCol', hide: true},
                        {field: 'id', title: 'ID', width: 60, align: 'center', hide: true},
                        {type: 'numbers', title: '序号', width: 60, align: 'center'},
                        {field: 'item', title: 'ITEM', width: 110, align: 'center'},
                        {field: 'ecu', title: 'ECU', width: 70, align: 'center'},
                        {field: 'ecu_feature', title: '特性', width: 120, align: 'center'},
                        {field: 'asset_code', title: '资产编码', width: 200, align: 'center'},
                        {field: 'security_attr', title: '安全属性', width: 110, align: 'center'},
                        {field: 'damage_scenario_desc', title: '损害场景描述', width: 330, align: 'left', edit: 'textarea', templet: function(d) {
                            return '<div class="auto-wrap">' + d.damage_scenario_desc + '</div>';
                        }, editOptions: {
                            type: 'textarea',
                            style: 'width: 100%; height: 100px;'
                        }},
                        {field: 'safe_affect_id', title: '安全影响', width: 150, align: 'center', templet: function(d) {
                            var html = '<select lay-filter="safeAffectIdSelect" lay-search lay-verify="required">';
                            for (var i = 0; i < safeAffectOptions.length; i++) {
                                html += '<option value="' + safeAffectOptions[i].id + '" ' + (safeAffectOptions[i].id == d.safe_affect_id ? 'selected' : '') + '>' + safeAffectOptions[i].name + '</option>';
                            }
                            html += '</select>';
                            return html;
                        }},
                        {field: 'economy_affect_id', title: '经济影响', width: 150, align: 'center', templet: function(d) {
                            var html = '<select lay-filter="economyAffectIdSelect" lay-search lay-verify="required">';
                            for (var i = 0; i < economyAffectOptions.length; i++) {
                                html += '<option value="' + economyAffectOptions[i].id + '" ' + (economyAffectOptions[i].id == d.economy_affect_id ? 'selected' : '') + '>' + economyAffectOptions[i].name + '</option>';
                            }
                            html += '</select>';
                            return html;
                        }},
                        {field: 'operator_affect_id', title: '操作影响', width: 150, align: 'center', templet: function(d) {
                            var html = '<select lay-filter="operatorAffectIdSelect" lay-search lay-verify="required">';
                            for (var i = 0; i < operatorAffectOptions.length; i++) {
                                html += '<option value="' + operatorAffectOptions[i].id + '" ' + (operatorAffectOptions[i].id == d.operator_affect_id ? 'selected' : '') + '>' + operatorAffectOptions[i].name + '</option>';
                            }
                            html += '</select>';
                            return html;
                        }},
                        {field: 'private_affect_id', title: '隐私影响', width: 150, align: 'center', templet: function(d) {
                            var html = '<select lay-filter="privateAffectIdSelect" lay-search lay-verify="required">';
                            for (var i = 0; i < privateAffectOptions.length; i++) {
                                html += '<option value="' + privateAffectOptions[i].id + '" ' + (privateAffectOptions[i].id == d.private_affect_id ? 'selected' : '') + '>' + privateAffectOptions[i].name + '</option>';
                            }
                            html += '</select>';
                            return html;
                        }},
                        {field: 'affect_value', title: '影响值', width: 100, align: 'center'},
                        {field: 'affect_level', title: '影响等级', width: 120, align: 'center'},
                    ]],
                    done: function (res, curr, count) {
                        console.log('表格渲染完成');
                        form.render('select');
                         // 强制同步列显示状态（处理表格重载时可能的状态不一致）
                        // 根据复选框的初始状态显示或隐藏checkbox列
                        var checkboxStatus = $('[name="enableCheckBox"]').prop('checked');
                        if(checkboxStatus) {
                            table.showCol(this.config.id, 'checkboxCol');
                        } else {
                            table.hideCol(this.config.id, 'checkboxCol');
                        }
                    }
                });
            }

            // 表格编辑事件
            table.on('edit(riskAssessmentTable)', function (obj) {
                var value = obj.value
                    , data = obj.data
                    , field = obj.field;

                fetch('/updateRiskAssessmentEcu', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        id: data.id,
                        field: field,
                        value: value
                    })
                })
                .then(response => response.json())
                .then(data => {
                    layer.msg(data.msg);
                });
            });

            // 安全影响下拉框选择事件
            form.on('select(safeAffectIdSelect)', function (data) {
                var value = data.value;
                var tr = data.othis.parents('tr');
                var rowData = table.cache['riskAssessmentTable'][tr.data('index')];
                //var key_id = rowData.id;
                var field = 'safe_affect_id';

                // 获取所有勾选的行ID
                var checkStatus = table.checkStatus('riskAssessmentTable');
                var checkedIds = checkStatus.data.map(item => item.id);
                var checkedRows = checkStatus.dataCache.map(item=> item.LAY_INDEX); //
                console.log('checkedRows=',checkedRows);
                // 若未勾选任何行，默认使用当前行（兼容原有逻辑）
                if (checkedIds.length === 0) checkedIds = [rowData.id];
                fetch('/batchUpdateRiskAssessment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        ids: checkedIds,
                        field: field,
                        value: value
                    })
                })
                .then(response => response.json())
                .then(data => {
                    layer.msg(data.msg);
                    if(checkedIds.length === 1) {
                        rowData.affect_value = data.affect_value; // 更新缓存中的数据
                        rowData.affect_level = data.affect_level; // 更新缓存中的数据
                        tr.find('td[data-field="affect_value"]').text(data.affect_value).css('text-align', 'center');
                        tr.find('td[data-field="affect_level"]').text(data.affect_level).css('text-align', 'center');
                    }else{
                        table.reloadData('riskAssessmentTable', {
                            done: function (res, curr, count) {
                                table.setRowChecked('riskAssessmentTable', {
                                  index: checkedRows
                                });
                            }
                        });

                    }
                });
            });

            // 经济影响下拉框选择事件
            form.on('select(economyAffectIdSelect)', function (data) {
                var value = data.value;
                var tr = data.othis.parents('tr');
                var rowData = table.cache['riskAssessmentTable'][tr.data('index')];
                //var key_id = rowData.id;
                var field = 'economy_affect_id';

               // 获取所有勾选的行ID
                var checkStatus = table.checkStatus('riskAssessmentTable');
                var checkedIds = checkStatus.data.map(item => item.id);

                var checkedRows = checkStatus.dataCache.map(item=> item.LAY_INDEX); //
                // 若未勾选任何行，默认使用当前行（兼容原有逻辑）
                if (checkedIds.length === 0) checkedIds = [rowData.id];
                fetch('/batchUpdateRiskAssessment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        ids: checkedIds,
                        field: field,
                        value: value
                    })
                })
                .then(response => response.json())
                .then(data => {
                    layer.msg(data.msg);
                    if(checkedIds.length === 1) {
                        rowData.affect_value = data.affect_value; // 更新缓存中的数据
                        rowData.affect_level = data.affect_level; // 更新缓存中的数据
                        tr.find('td[data-field="affect_value"]').text(data.affect_value).css('text-align', 'center');
                        tr.find('td[data-field="affect_level"]').text(data.affect_level).css('text-align', 'center');
                    }else{
                        table.reloadData('riskAssessmentTable', {
                            done: function (res, curr, count) {
                                table.setRowChecked('riskAssessmentTable', {
                                  index: checkedRows
                                });
                            }
                        });
                    }
                });
            });

            // 操作影响下拉框选择事件
            form.on('select(operatorAffectIdSelect)', function (data) {
                var value = data.value;
                var tr = data.othis.parents('tr');
                var rowData = table.cache['riskAssessmentTable'][tr.data('index')];
                {#var key_id = rowData.id;#}
                var field = 'operator_affect_id';

                // 获取所有勾选的行ID
                var checkStatus = table.checkStatus('riskAssessmentTable');
                var checkedIds = checkStatus.data.map(item => item.id);
                var checkedRows = checkStatus.dataCache.map(item=> item.LAY_INDEX); //
                // 若未勾选任何行，默认使用当前行（兼容原有逻辑）
                if (checkedIds.length === 0) checkedIds = [rowData.id];
                fetch('/batchUpdateRiskAssessment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        ids: checkedIds,
                        field: field,
                        value: value
                    })
                })
                .then(response => response.json())
                .then(data => {
                    layer.msg(data.msg);
                    if(checkedIds.length === 1) {
                        rowData.affect_value = data.affect_value; // 更新缓存中的数据
                        rowData.affect_level = data.affect_level; // 更新缓存中的数据
                        tr.find('td[data-field="affect_value"]').text(data.affect_value).css('text-align', 'center');
                        tr.find('td[data-field="affect_level"]').text(data.affect_level).css('text-align', 'center');
                    }else{
                        table.reloadData('riskAssessmentTable', {
                            done: function (res, curr, count) {
                                table.setRowChecked('riskAssessmentTable', {
                                  index: checkedRows
                                });
                            }
                        });
                    }
                });
            });

            // 隐私影响下拉框选择事件
            form.on('select(privateAffectIdSelect)', function (data) {
                var value = data.value;
                var tr = data.othis.parents('tr');
                var rowData = table.cache['riskAssessmentTable'][tr.data('index')];
                var key_id = rowData.id;
                var field = 'private_affect_id';

                // 获取所有勾选的行ID
                var checkStatus = table.checkStatus('riskAssessmentTable');
                var checkedIds = checkStatus.data.map(item => item.id);
                var checkedRows = checkStatus.dataCache.map(item=> item.LAY_INDEX); //

                // 若未勾选任何行，默认使用当前行（兼容原有逻辑）
                if (checkedIds.length === 0) checkedIds = [rowData.id];
                fetch('/batchUpdateRiskAssessment', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        ids: checkedIds,
                        field: field,
                        value: value
                    })
                })
                .then(response => response.json())
                .then(data => {
                    layer.msg(data.msg);
                    if(checkedIds.length === 1) {
                        rowData.affect_value = data.affect_value; // 更新缓存中的数据
                        rowData.affect_level = data.affect_level; // 更新缓存中的数据
                        tr.find('td[data-field="affect_value"]').text(data.affect_value).css('text-align', 'center');
                        tr.find('td[data-field="affect_level"]').text(data.affect_level).css('text-align', 'center');
                    }else{
                        table.reloadData('riskAssessmentTable', {
                            done: function (res, curr, count) {
                                table.setRowChecked('riskAssessmentTable', {
                                  index: checkedRows
                                });
                            }
                        });
                    }
                });
            });
        });
    </script>
</body>
</html>